const express = require('express');
const router = express.Router();
const fs = require('fs')
const {readFilePrms, writeFilePrms} = require('../utils/fsPrms')
const qiniu = require('qiniu')

qiniu.conf.ACCESS_KEY = 'RQKuDMYcuK_5DWeTV_eJrIAhrljPpzrpjIXMT7za'
qiniu.conf.SECRET_KEY = 'k6ST9cFBVmaLTzJJsgg9QNwzCbeEqGPj3Rv1qanL'

const bucket = 'photo'
const key = 'test.jpg'

function uptoken(bucket) {
    var putPolicy = new qiniu.rs.PutPolicy(bucket);
    return putPolicy.token();
}

router.get('/', (req, res, next) => {
    const title = 'Blink Photo';
    res.renderPage('index', {
        title: title,
    });
});

router.get('/activity/:id', (req, res, next) => {
    const title = '活动页面';
    res.renderPage('activity', {
        title: title,
    }, 'mobile');
});

router.get('/api/getUploadToken', (req, res, next) => {
    let time = new Date().getTime()
    let _TOKEN
    // let key = `${req.params.actID}/${req.params.cameraID}/${req.params.imgName}` || 'test.jpg'
    // console.log(key)
    readFilePrms('./routes/upload.json').then(raw => {
        let tokenCached = JSON.parse(raw.data)
        if (time - tokenCached.time > 59 * 60 * 1000) {
            let token = uptoken(bucket);
            writeFilePrms('./routes/upload.json', JSON.stringify({token, time}))
                .then(() => {
                    console.log('token写入完成');
                }).catch(err => {
                console.log(err);
            });
            _TOKEN = token
        } else {
            console.log('读取缓存token缓存！');
            _TOKEN = tokenCached.token
        }
        res.json({
            success: true,
            token: _TOKEN,
            message: '猜猜这是干什么的'
        });
    }).catch(e => {
        console.log(e)
        res.json({
            success: false,
            token: 'xxxx',
            message: '别看了，失败了'
        });
    })
});

router.use('/api/v1', require('./ajax'));

module.exports = router;


